package net;

import java.io.IOException;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import lmf.AlbumArrayLFM;
import lmf.AlbumLFM;
import lmf.ArtistLFM;
import lmf.TrackArrayLFM;
import lmf.WeeklyChartLFM;
import musicbrainz.*;

import applet.GLOBALS;

public class HTTPConnection implements GLOBALS{
	
	URLConnection urlConnection;
	
	public HTTPConnection() {
	}
	public AlbumLFM getAlbumInfoLFM(String mbid){
		if(mbid == null || mbid.equals(""))
			return null;
		  try {
	            //without proxy:
	            urlConnection = new URL(LFM_URL + LFM_GETALBUMINFO + LFM_MBID + mbid + LFM_api_key).openConnection();

	            System.out.println(urlConnection.getURL());
	            setConnectionProperties();

	            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
	                    .newInstance();
	            DocumentBuilder builder = dbFactory.newDocumentBuilder();
	            Document doc = builder.parse(urlConnection.getInputStream());
	            
	            doc.getDocumentElement ().normalize ();
	            //printDoc(doc);
	            
	            
	            return new AlbumLFM(doc);
	        } catch (MalformedURLException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (ParserConfigurationException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (SAXException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	        catch (Exception e) {
				e.printStackTrace();
			}
			return null;
	}
	
	public TrackArrayLFM getTracksByAlbumLFM(String album_mbid){
		if(album_mbid == null || album_mbid.equals(""))
			return null;
		  try {
	            //without proxy:
	            urlConnection = new URL(LFM_URL + LFM_GETALBUMINFO + LFM_MBID + album_mbid + LFM_api_key).openConnection();

	            System.out.println(urlConnection.getURL());
	            setConnectionProperties();

	            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
	                    .newInstance();
	            DocumentBuilder builder = dbFactory.newDocumentBuilder();
	            Document doc = builder.parse(urlConnection.getInputStream());
	            
	            doc.getDocumentElement ().normalize ();
	            //printDoc(doc);
	            
	            
	            return new TrackArrayLFM(doc);
	        } catch (MalformedURLException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (ParserConfigurationException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (SAXException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	        catch (Exception e) {
				e.printStackTrace();
			}
			return null;
	}
	
	public AlbumArrayLFM getTopAlbumsByArtist(String artist_mbid){
		if(artist_mbid == null || artist_mbid.equals(""))
			return null;
		  try {
	            //without proxy:
	            urlConnection = new URL(LFM_URL + LFM_GETTOPALBUMS + LFM_MBID + artist_mbid + LFM_api_key).openConnection();

	            System.out.println(urlConnection.getURL());
	            setConnectionProperties();

	            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
	                    .newInstance();
	            DocumentBuilder builder = dbFactory.newDocumentBuilder();
	            Document doc = builder.parse(urlConnection.getInputStream());
	            
	            doc.getDocumentElement ().normalize ();
	            printDoc(doc);
	            
	            
	            return new AlbumArrayLFM(doc);
	        } catch (MalformedURLException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (ParserConfigurationException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (SAXException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	        catch (Exception e) {
				e.printStackTrace();
			}
			return null;
	}
	
	public WeeklyChartLFM getLFMWeeklyChart(){
        try {
            //without proxy:
            urlConnection = new URL(LFM_URL + LFM_GETWEEKLY_ARTIST_CHAR + LFM_GROUP_MNML + LFM_api_key).openConnection();

            System.out.println(urlConnection.getURL());
            setConnectionProperties();

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = dbFactory.newDocumentBuilder();
            Document doc = builder.parse(urlConnection.getInputStream());
            
            doc.getDocumentElement ().normalize ();
            //printDoc(doc);
            
            
            return new WeeklyChartLFM(doc);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public ArtistLFM getLFMArtistInfo(String artist_mbid){
		if(artist_mbid == null || artist_mbid.equals(""))
			return null;
        try {
            //without proxy:
            urlConnection = new URL(LFM_URL + LFM_GETARTIST + "&mbid=" + artist_mbid + LFM_api_key).openConnection();
            
            //with
            //urlConnection = new URL("http","10.241.32.28",8080,MB_URL + MB_ARTIST + FORWARD_SLASH + mbid).openConnection();

            System.out.println(urlConnection.getURL());
            setConnectionProperties();

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = dbFactory.newDocumentBuilder();
            Document doc = builder.parse(urlConnection.getInputStream());
            
            doc.getDocumentElement ().normalize ();
            //printDoc(doc);
            
            
            return new ArtistLFM(doc);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
    public RecordingArrayMB getMBSongInfoFromRelease(String release_mbid){
		if(release_mbid == null || release_mbid.equals(""))
			return null;
        try {
            //without proxy:
            urlConnection = new URL(MB_URL + MB_RECORDING + "?" + MB_RELEASE +"="+ release_mbid).openConnection();
            
            //with
            //urlConnection = new URL("http","10.241.32.28",8080,MB_URL + MB_ARTIST + FORWARD_SLASH + mbid).openConnection();

            System.out.println(urlConnection.getURL());
            setConnectionProperties();

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = dbFactory.newDocumentBuilder();
            Document doc = builder.parse(urlConnection.getInputStream());
            
            doc.getDocumentElement ().normalize ();
            //printDoc(doc);
            
            
            return new RecordingArrayMB(doc);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (Exception e) {
			e.printStackTrace();
		}
        return null;
    }
	
	  public RecordingArrayMB getMBSongInfoFromArtists(String artist_mbid, int limit, int offset){
			if(artist_mbid == null || artist_mbid.equals(""))
				return null;
	        try {
	            //without proxy:
	            urlConnection = new URL(MB_URL + MB_RECORDING + "?" + MB_ARTIST +"="+ artist_mbid +"&limit="+limit+"&offset="+offset).openConnection();
	            
	            //with
	            //urlConnection = new URL("http","10.241.32.28",8080,MB_URL + MB_ARTIST + FORWARD_SLASH + mbid).openConnection();

	            System.out.println(urlConnection.getURL());
	            setConnectionProperties();

	            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
	                    .newInstance();
	            DocumentBuilder builder = dbFactory.newDocumentBuilder();
	            Document doc = builder.parse(urlConnection.getInputStream());
	            
	             doc.getDocumentElement ().normalize ();
	                System.out.println ("Root element of the doc is " + 
	                     doc.getDocumentElement().getNodeName());
	            
	                //printDoc(doc);
	                
	            NodeList nl = doc.getElementsByTagName("name");
	            System.out.println(nl.item(0).getFirstChild().getNodeValue());
	            
	            RecordingArrayMB a = new RecordingArrayMB(doc);
	            return a;
	        } catch (MalformedURLException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (ParserConfigurationException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (SAXException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	        catch (Exception e) {
				e.printStackTrace();
			}
	        return null;
	    }
	
	
	public ReleaseArrayMB getMBReleaseInfoFromArtist(String artist_mbid, int limit, int offset){
		if(artist_mbid == null || artist_mbid.equals(""))
			return null;
		try {
			urlConnection = new URL(MB_URL + MB_RELEASE + "?" + MB_ARTIST +"="+  artist_mbid +"&type=album"+"&limit="+limit+"&offset="+offset).openConnection();
			setConnectionProperties();
			
            System.out.println(urlConnection.getURL());
            setConnectionProperties();

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = dbFactory.newDocumentBuilder();
            Document doc = builder.parse(urlConnection.getInputStream());
            
             doc.getDocumentElement ().normalize ();
             //printDoc(doc);
            
             ReleaseArrayMB a = new ReleaseArrayMB(doc);
            return a;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	public ArtistMB getMBAristInfo(String mbid){
		if(mbid == null || mbid.equals(""))
			return null;
		try {
		    //without proxy:
			urlConnection = new URL(MB_URL + MB_ARTIST + FORWARD_SLASH + mbid ).openConnection();
			
		    //with
		    //urlConnection = new URL("http","10.241.32.28",8080,MB_URL + MB_ARTIST + FORWARD_SLASH + mbid).openConnection();

			System.out.println(urlConnection.getURL());
			setConnectionProperties();

			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = dbFactory.newDocumentBuilder();
			Document doc = builder.parse(urlConnection.getInputStream());
			
	        //printDoc(doc);
	            
	        NodeList nl = doc.getElementsByTagName("name");
			System.out.println(nl.item(0).getFirstChild().getNodeValue());
			
			ArtistMB a = new ArtistMB(doc);
			return a;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	void setConnectionProperties(){
		urlConnection.setUseCaches(false);
		//urlConnection.setDoOutput(true); // Triggers POST.
		urlConnection.setRequestProperty("accept-charset", CHARSET);
		//urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
	}
	
	void printDoc(Document doc){
	    Transformer transformer = null;
        try {
            transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            //initialize StreamResult with File object to save to file
            StreamResult result = new StreamResult(new StringWriter());
            DOMSource source = new DOMSource(doc);
            transformer.transform(source, result);

            String xmlString = result.getWriter().toString();
            System.out.println(xmlString);
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerFactoryConfigurationError e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	public static void main(String arg[]){
	    Properties props = System.getProperties();
	    //props.put("http.proxyHost", "10.241.32.28");
	    //props.put("http.proxyPort", "8080");
	    
		HTTPConnection http = new HTTPConnection();
		ArtistMB artist =  http.getMBAristInfo("0036fc0e-4e33-3ac8-8974-ea124079c978");
		// = new ArtistMB(artDoc);
		AlbumLFM a1 = http.getAlbumInfoLFM("0036fc0e-4e33-3ac8-8974-ea124079c978");
		ReleaseArrayMB releases = http.getMBReleaseInfoFromArtist("b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d", 10, 0);
		//ReleaseArrayMB r = new ReleaseArrayMB(doc2);
		//http.getMBSongInfoFromArtists("b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d", 10, 0);
		//Document songDoc = http.getMBSongInfoFromRelease("fb3bf1c9-38cd-453d-8c7d-60823cffe5a8");
		//RecordingArrayMB rec = new RecordingArrayMB(songDoc);
		//Document doc = http.getLFMArtistInfo("b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d");
		//ArtistLFM al = new ArtistLFM(doc);
		//http.getLFMWeeklyChart();
		//AlbumArrayLFM arr = http.getTopAlbumsByArtist("b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d");
		AlbumArrayLFM arr = http.getTopAlbumsByArtist("bfcc6d75-a6a5-4bc6-8282-47aec8531818");
		TrackArrayLFM t = http.getTracksByAlbumLFM("61bf0388-b8a9-48f4-81d1-7eb02706dfb0");
		System.out.println(t);
	}
	
}
